<?php

namespace App\Http\Controllers;

use App\Models\AdminOperationRecord;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Request;
use Modules\Admin\Auth\Facades\AdminAuth;

class Controller extends BaseController
{
    /**
     * @var string $hollycrmAccessToken 合力亿捷客服系统获取鉴权
     */
    private $hollycrmAccessToken = 'http://a1.7x24cc.com/accessToken?account=N000000014533&appid=v2l4fcfpwuerk9&secret=b61fd190-82b9-11e9-b758-e791be65cf05';
    /**
     * @var string $hollycrmCall 合力亿捷客服系统拨打电话
     */
    private $hollycrmCall = 'http://a1.7x24cc.com/commonInte?flag=106&account=N000000014533&phonenum={phonenum}&integratedid={integratedid}&accessToken={accessToken}';

    public function __construct()
    {
    }

    protected function recordAction($message,$before_data = [],$client_ip = null)
    {
        $data = [];
        $admin = AdminAuth::user();
        if($admin) {
            $data['admin_id'] = $admin['id'];
            $data['username'] = $admin['username'];
            $data['type'] = 'system';
            $data['message'] = $message;
            $data['before_data'] = serialize($before_data);
            $data['client_ip'] = $client_ip ? : request()->getClientIp();
            (new AdminOperationRecord())->query()->create($data);
        }
    }

    /**
     * 拨打电话
     *
     * @author yls
     * @param $mobile
     * @return bool|mixed
     */
    protected function hollycrmCall($mobile)
    {
        if (empty($mobile)) {
            return false;
        }

        $accessToken = $this->getAccessToken();
        if (empty($accessToken)) {
            return false;
        }

        $url = $this->hollycrmCall;
        $admin = AdminAuth::user();
        if($admin) {
            $kefuNo = $admin['kefu_no'];
            if (empty($kefuNo)) {
                return false;
            }
            $url = str_replace(['{accessToken}', '{phonenum}', '{integratedid}'], [$accessToken, $mobile, $kefuNo], $url);
            $res = self::fetch($url, [], 'get');
            if (1 == $res['error_code']) {
                return $res['data'];
            } else {
                return $res['data'];
            }
        } else {
            return false;
        }

    }

    /**
     * 获取accessToken
     *
     * @author yls
     * @return mixed|string
     */
    private function getAccessToken()
    {
        $result = self::fetch($this->hollycrmAccessToken, [], 'get');
        if (1 == $result['error_code']) {
            return '';
        }
        $data = json_decode($result['data'], true);
        return $data['accessToken'] ?? '';
    }

    /**
     * post curl
     *
     * @author yls
     * @param       $url
     * @param array $data
     * @return array
     */
    public static function post($url, $data=[])
    {
        $result = self::fetch($url, $data, 'post');
        return $result;
    }

    /**
     * curl
     *
     * @author yls
     * @param        $url
     * @param array  $data
     * @param string $type
     * @return array
     */
    public static function fetch($url, $data=[], $type='post') {
        $isHttps = preg_match('/^https?:/i', $url) > 0 ? true : false;
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            if($isHttps == true){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            }

            if($type == 'post'){
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            $result = curl_exec($ch);
            if($result === false){
                $res = ['error_code'=>1, 'msg'=>curl_error($ch)];
                return $res;
            }
            $info = curl_getinfo($ch);
            if($info['http_code'] != '200'){
                $res = ['error_code'=>1, 'msg'=>$info['http_code']];
                return $res;
            }
            curl_close($ch);
            $res = ['error_code'=>0, 'data'=>$result];
            return $res;
        }catch (\Exception $e){
            $res = ['error_code'=>1, 'msg'=>$e->getMessage()];
            return $res;
        }
    }
}
